<template>
  <div>
    <a-card class="card">
      <template slot="title" >
        <span style="display:flex;align-items: center;">
          直播间数据总表
          <a-tooltip style="margin-left:6px;">
            <template slot="title">
              直播间数据总表
            </template>
            <a-icon style="cursor: pointer;" type="exclamation-circle" :style="{ fontSize: '12px',color:'#888888' }"/>
          </a-tooltip>
        </span>
      </template>
      <div class="area">
        <a-button type="primary" @click="handle_export" style="margin-bottom:20px; margin-right: 10px;">导出</a-button>
        <a-select v-model="chartTimeSelect" style="width: 180px" @change="selectChange">
          <a-select-option :value="3">当日</a-select-option>
          <a-select-option :value="1">昨日</a-select-option>
          <a-select-option :value="7">过去一周</a-select-option>
          <a-select-option :value="4">过去30天</a-select-option>
          <a-select-option :value="5">本月</a-select-option>
          <a-select-option :value="6">本季度</a-select-option>
          <a-select-option :value="9">2022下半年</a-select-option>
          <a-select-option :value="8">自定义</a-select-option>
        </a-select>
        <a-range-picker
          :allowClear="false"
          :ranges="{ '昨天': [moment().add(-1, 'days'), moment().add(-1, 'days')], '过去7天': [moment().add(-7, 'days'), moment().add(-1, 'days')], 
                    '过去30天': [moment().add(-30, 'days'), moment().add(-1, 'days')] }"
          :defaultValue="[moment().add(-1, 'days'), moment().add(-1, 'days')]"
          :disabled-date="disabledDate" @change="formDateChange" style="margin-left:20px;width:240px;margin-bottom: 20px;" 
          v-if="chartTimeSelect == 8"
        />
      </div>
      <a-table
        id="zhiboTable"
        ref="table"
        :loading='loading'
        :columns="columns"
        :dataSource="dataSource"
        :scroll="{x:1200}"
        :pagination="pagination()"
        @change="onChange"
      >
        <div slot="ctr" slot-scope="record">
          {{(record*100).toFixed(2) + '%'}}
        </div>
        <div slot="cvr" slot-scope="record">
          {{record?(record*100).toFixed(2) + '%':'0%'}}
        </div>
        <div slot="cost" slot-scope="record">
          {{(record).toFixed(2)}}
        </div>
        <div slot="cpm" slot-scope="record">
          {{(record).toFixed(2)}}
        </div>
        <div slot="ROI" slot-scope="record">
          {{(record).toFixed(2)}}
        </div>
        <div slot="huan_cost" slot-scope="record">
          {{(record).toFixed(2)}}
        </div>
        <div slot="liveOrderConversions" slot-scope="record">
          {{record}} 
        </div>
        <div slot="liveOrderAmountConversions" slot-scope="record">
          {{record.toFixed(2)}} 
        </div>
      </a-table>
    </a-card>  
  </div>
</template>

<script>
// import StandardTable from '@/components/table/StandardTable'
import {getLiveReport} from '@/api/shuju/shuju'
import FileSaver from 'file-saver';
import XLSX from 'xlsx';
import moment from 'moment';

const columns = [
  {
    title: '品类',
    width: 100,
    dataIndex: 'category'
  },
  {
    title: '货品名',
    width: 150,
    dataIndex: 'product_name'
  },
  {
    title: '百家号昵称',
    width: 150,
    dataIndex: 'bdname'
  },
  {
    title: '账户',
    width: 150,
    dataIndex: 'userName'
  },
  {
    title: '优化师',
    width: 100,
    dataIndex: 'optimizer'
  },
  {
    title: '点击量',
    width: 100,
    dataIndex: 'click'
  },
  {
    title: '消费',
    width: 100,
    dataIndex: 'cost',
    scopedSlots: { customRender: 'cost' },
  },
  {
    title: '支付订单数',
    width: 150,
    dataIndex: 'liveOrderConversions',
    scopedSlots: { customRender: 'liveOrderConversions' },
  },
  {
    title: '点击率(CTR)',
    width: 100,
    dataIndex: 'ctr',
    scopedSlots: { customRender: 'ctr' },
  },
  {
    title: '成单转换率(CVR)',
    width: 150,
    dataIndex: 'cvr',
    scopedSlots: { customRender: 'cvr' },
  },
  {
    title: '千次展现消费(CPM)',
    width: 150,
    dataIndex: 'cpm',
    scopedSlots: { customRender: 'cpm' },
  },
  {
    title: '商品订单金额(GMV)',
    width: 150,
    dataIndex: 'liveOrderAmountConversions',
    scopedSlots: { customRender: 'liveOrderAmountConversions' },
  },
  {
    title: '账面ROI',
    width: 150,
    dataIndex: 'ROI',
    scopedSlots: { customRender: 'ROI' },
  },
]
export default {
  name:'zhiboData',
  data() {
    return {
      moment,
      columns,
      loading:false,
      dataSource:[],
      total:0,
      changeKey:'ctProductPaySuccess',
      changeOrder:'DESC',
      chartTimeSelect:3,
      start_date: moment().add(-1, 'days').format("YYYY-MM-DD"),
      end_date: moment().add(-1, 'days').format("YYYY-MM-DD"),
      isExport: false, // 是否在导出中
    }
  },
  created(){
    this.getQiliangData()
  },
  mounted(){
    // console.log(this.$refs)
    // const tableCon = this.$refs['table']
    // const table = tableCon.querySelector('table')
    // table.setAttribute('id','table-to-xls')
  },
  methods:{
    getQiliangData(){
      this.loading = true
      let params = {
        live_type: this.chartTimeSelect,
      }
      if(this.chartTimeSelect == 8){
        Object.assign(params, {
          start_date: this.start_date,
          end_date: this.end_date,
        })
      }
      getLiveReport(params).then((res) => {
        this.loading = false
        let key = 1
        for(let item of res.data){
          item['key'] = key++
        }
        if(res.errcode == 0){
          this.dataSource = res.data
          this.total = res.data.length
        }
      }).catch(() => {
        this.loading = false
      });
    },
    getSorter(sorter){
      if(sorter.column){
        this.changeKey = sorter.column.dataIndex
        switch(sorter.order){
          case "ascend":
            this.changeOrder = 'ASC'
            break
          case "descend":
            this.changeOrder = 'DESC'
            break
        }
      }else{
        this.changeKey = ''
        this.changeOrder = ''
      }
    },
    selectChange(){
      this.getQiliangData()
    },
    onChange(pagination, filters, sorter,) {
      // console.log(pagination, filters, sorter)
      this.getSorter(sorter)
      this.page = pagination.current
      // this.getQiliangData()
    },
    pagination(){
      if(!this.isExport){
        // 没在导出中则显示完整分页
        return {showTotal:total => `共 ${total} 条数据`,showSizeChanger:true}
      }else{
        return false
      }
    },
    handle_export() {
      this.isExport = true
      setTimeout(() => {
          var xlsxParam = {
          raw: true
        }; //转换成excel时，使用原始的格式，这样导出的时候数字过长不会变成科学计数法
        let workbook = XLSX.utils.book_new();
        let ws1 = XLSX.utils.table_to_sheet(document.querySelector('#zhiboTable'), xlsxParam);
        XLSX.utils.book_append_sheet(workbook, ws1, '直播报表');
        let wbout = XLSX.write(workbook, {
            bookType: 'xlsx',
            bookSST: true,
            type: 'array'
        });
        try {
            FileSaver.saveAs(
            new Blob([wbout], {
                type: 'application/octet-stream;charset=utf-8"'
            }), '直播报表.xlsx');
        } catch (e) {
            if (typeof console !== 'undefined') console.log(e, wbout);
        }
        this.isExport = false
        return wbout;
      }, 0);
    },
    formDateChange(e){
      if(e.length == 0){return}
      this.start_date = e[0].format("YYYY-MM-DD")
      this.end_date = e[1].format("YYYY-MM-DD")
      this.getQiliangData()
    },
    disabledDate(current){
      return current && ( current < moment().endOf('day').add(-31, 'days') || current > moment().endOf('day').add(-1, 'days')) ;
    },
  },
  components:{}
}
</script>

<style lang="less" scoped>

</style>